package com.xh.demo.datasource;

import com.xh.demo.datasource.enums.DataSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Objects;

@Slf4j
public class ThreadLocalRouteDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<DataSourceEnum> THREAD_LOCAL_DATA_SOURCE_KEY = new ThreadLocal<>();

    public static void clear() {
        log.info("清除当前线程数据源");
        THREAD_LOCAL_DATA_SOURCE_KEY.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        DataSourceEnum dataSourceEnum = THREAD_LOCAL_DATA_SOURCE_KEY.get();
        String dataSource = Objects.isNull(dataSourceEnum) ? DataSourceEnum.MASTER.name() : dataSourceEnum.name();
        log.info("通过key确定当前应该使用哪个数据源, key:{}", dataSource);
        return dataSource;
    }

    public static void setDataSourceKey(DataSourceEnum dataSourceEnum) {
        log.info("设置需要使用的数据源key, key:{}", dataSourceEnum.name());
        THREAD_LOCAL_DATA_SOURCE_KEY.set(dataSourceEnum);
    }

}